<?php

namespace App\Http\Controllers;

use App\Http\Requests\Api\SendCaptcha;
use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;
use Illuminate\Support\Facades\Cache;
use Symfony\Component\HttpKernel\Exception\HttpException;

class CaptchaController extends Controller
{
    /**
     * @param SendCaptcha $request
     * @return mixed
     * @throws \Exception
     */
    public function store(SendCaptcha $request)
    {
        $mobile = $request->input('mobile');
        $key = 'phone_verification_expired:' . $request->input('mobile');
        $unexpired = Cache::get($key);
        if ($unexpired) {
            return $this->failed('验证码已发送，请勿重复请求', 40010);
        }

        $code = str_pad(random_int(1, 9999), 4, 0, STR_PAD_LEFT);;//短信验证码
        // 缓存验证码
        Cache::put('phone_verification:'. $mobile, $code, now()->addMinutes(3));
        Cache::put('phone_verification_expired:' . $mobile, 1, now()->addMinutes(2));

        // 发送短信
        $url = 'https://angelapi.bluemoon.com.cn/moonMall-proxy-web/sms/sendMsgByMobile';//测试
        // $url = 'http://mallapi.bluemoon.com.cn/moonMall-proxy-web/sms/sendMsgByMobile';//正式
        $postData = [
            'content' => '您好，短信验证码：'.$code,
            'myAccount' => 'xfzfw',
            'mobileNo' => $mobile,
            'myProjectName' => '消费者服务号',
            'myRemark' => '电商消费者服务项目调用短信',
        ];

        $client = new Client();
        $options = [
            RequestOptions::JSON => $postData,
        ];
        $response = $client->post($url, $options);
        $respond = json_decode($response->getBody()->getContents(), true);

        if ($respond['isSuccess'] === false) {
            throw new HttpException(400, $respond['responseMsg'], null, [], $respond['responseCode']);
        }

        if (app()->environment() == 'local') {
            return $this->success(['code' => $code], '发送成功');
        }

        return $this->message('发送成功');
    }
}
